package com.cpi.cornpp.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import KC.ModSegApp.EntidadModSegApp;
import KC.ModSegApp.UsuarioApp;

import com.cpi.cornpp.user.view.UserView;
import com.cs.common.init.PermissionCollection;
import com.cs.common.init.beans.PermissionBean;

public class AutorizationCornPPFilter implements Filter{
	/** Nombre de variable de session para el usuario */
	private static final String USER_SESSION_NAME = "user";
	/** Acci�n de error */
	private static final String NO_PERMISSION_ACTION = "/noPermission.do";
	/** Init filter config */
	private FilterConfig filterConfig = null;
	/** usuario de la Aplicacion*/
	private UsuarioApp usuarioApp;
	/** ADMINISTRACION */
	
	
	
	public void destroy() {
		filterConfig = null;
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = null;
		HttpServletResponse httpServletResponse = null;
		HttpSession httpSession =  null;
		String requestUri = null;
		UserView userView = null;
		String contextPath = null;		
		httpServletRequest = (HttpServletRequest)servletRequest;
		httpServletResponse = (HttpServletResponse)servletResponse;
		contextPath = httpServletRequest.getContextPath();
		requestUri= httpServletRequest.getServletPath();
		httpSession =  httpServletRequest.getSession();
		userView = (UserView)httpSession.getAttribute(USER_SESSION_NAME);		
				
		if( requestUri!=null ){
			/*Intentar localizar permiso para la accion solicitada*/
			PermissionBean pBean = PermissionCollection.getInstance().getPermissionBean(requestUri);
			if(pBean== null ){
				filterChain.doFilter(servletRequest, servletResponse);
			}	
			/*Si existe el permiso validar contra el usuario logueado*/
			 if(pBean!=null && pBean.getAction().equals(requestUri) && userView != null   ){
				usuarioApp =  (UsuarioApp) userView.getUserObject();
				if (usuarioApp.getAplicacionAValidar().getPermiso(pBean.getModule(),pBean.getSubmodule(), pBean.getEntity(), EntidadModSegApp.ADMINISTRACION)) {
					filterChain.doFilter(servletRequest, servletResponse);
				}else{
					httpServletResponse.sendRedirect(new StringBuffer(contextPath).append(NO_PERMISSION_ACTION).toString());
				}				
			 }
			}else{
				 filterChain.doFilter(servletRequest, servletResponse);
			 }
		
	}

	public void init(FilterConfig fConfig) throws ServletException {
		filterConfig = fConfig;
		System.out.println(filterConfig);
	}	
}